#!/usr/bin/env python
# encoding: utf-8
"""
@author:shucheng
@file:json_util.py
@time:2024/1/4 22:55
@desc
"""
import json
import os.path
from json import JSONDecodeError

from util import file_tool


def pretty_format_json(json_str):
    """
    将json字符串进行美化
    :param json_str:
    :return:
    """
    obj = json.loads(json_str)
    return json.dumps(obj, indent=2, ensure_ascii=False)


def read_json(file_path):
    """
    读取json数据
    :param file_path:
    :return:
    """
    if not os.path.exists(file_path):
        return {}

    try:
        with open(file_path, "r", encoding="utf-8") as file:
            result = json.load(file)
    except JSONDecodeError:
        result = {}
    return result


def write_json(file_path, input_obj, need_pretty=False):
    """
    将json写入文件
    :param file_path:
    :param input_obj:
    :param need_pretty: 是否需要美化，默认为False
    :return:
    """
    # 如果父级文件夹不存在，则先创建父级文件夹
    file_tool.ensure_parent_dir_exists(file_path)

    """
    lsc补充：json.dumps和json.dump的区别
    json.dumps是将python对象序列化为json字符串，json.dump是将python对象序列化为json并写入文件
    参考链接：http://www.mobiletrain.org/about/BBS/253101.html
    """

    # dict和list都能正常使用json.dump，无需做特殊处理
    # 特殊情况处理：set不能直接用json.dump，需要先转换为list
    # 参考链接：https://blog.51cto.com/u_16213381/8398189
    if isinstance(input_obj, set):
        input_obj = list(input_obj)

    # 将json字符串写入文件
    with open(file_path, "w", encoding="utf-8") as file:
        if need_pretty:
            json.dump(input_obj, file, ensure_ascii=False, indent=2)
        else:
            json.dump(input_obj, file, ensure_ascii=False)
